package org.chen.translate.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.chen.common.translate.dto.BaiduTranslateRequestDTO;
import org.chen.common.translate.dto.BaiduTranslateResponseDTO;
import org.chen.common.translate.result.ResultVO;
import org.chen.translate.service.BaiduTranslateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("/baidu-translate")
@Validated
public class BaiduTranslateController {
    
    @Autowired
    private BaiduTranslateService baiduTranslateService;
    
    /**
     * POST方式翻译文本
     */
    @PostMapping("/translate")
    @Tag(name = "百度翻译接口", description = "腾讯云翻译相关接口")
    @Operation(summary = "POST翻译文本", description = "使用POST方式翻译文本")
    public BaiduTranslateResponseDTO translateText(@Valid @RequestBody BaiduTranslateRequestDTO request) {

        try {
            // 设置默认值
            if (request.getFromLang() == null || request.getFromLang().trim().isEmpty()) {
                request.setFromLang("en");
            }
            if (request.getToLang() == null || request.getToLang().trim().isEmpty()) {
                request.setToLang("zh");
            }

            // 执行翻译

            return baiduTranslateService.translateText(request);

        } catch (Exception e) {

            String errorMessage = handleBaiduError(e);

            throw new RuntimeException(errorMessage);
        }
    }
    
    /**
     * GET方式翻译文本
     */
    @GetMapping("/translate")
    @Tag(name = "百度翻译接口", description = "腾讯云翻译相关接口")
    @Operation(summary = "GET翻译文本", description = "使用GET方式翻译文本（与POST方式功能相同）")
    public BaiduTranslateResponseDTO translateGet(
            @Parameter(description = "待翻译文本", required = true)
            @RequestParam @NotBlank(message = "待翻译文本不能为空") String q,
            
            @Parameter(description = "原文语言代码", example = "en")
            @RequestParam(defaultValue = "en") String from_lang,
            
            @Parameter(description = "译文语言代码", example = "zh")
            @RequestParam(defaultValue = "zh") String to_lang) {
        
        // 构建请求对象
        BaiduTranslateRequestDTO request = new BaiduTranslateRequestDTO(q, from_lang, to_lang);
        
        // 调用POST方法
        return translateText(request);
    }
    
    /**
     * 获取限流状态
     */
    @GetMapping("/status")
    @Tag(name = "查询限流状态")
    @Operation(summary = "查询百度翻译限流状态", description = "查询百度翻译服务的限流状态")
    public ResultVO getRateLimitStatus() {
        try {
            String status = baiduTranslateService.getRateLimitStatus();
            return ResultVO.success(status);
        } catch (Exception e) {
            return ResultVO.fail("查询状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置限流器
     */
    @PostMapping("/reset-limiter")
    @Tag(name = "重置限流器", description = "紧急情况下重置限流器")
    @Operation(summary = "重置百度翻译限流器", description = "紧急情况下重置百度翻译限流器")
    public ResultVO resetRateLimiter() {
        try {
            baiduTranslateService.resetRateLimiter();
            return ResultVO.success("百度翻译限流器已重置");
        } catch (Exception e) {
            return ResultVO.fail("重置限流器失败：" + e.getMessage());
        }
    }

    /**
     * 处理百度翻译特定错误
     */
    private String handleBaiduError(Exception e) {
        String message = e.getMessage();
        if (message == null) return "未知错误";
        
        // 百度翻译错误代码处理
        if (message.contains("52001")) {
            return "请求超时，请稍后重试";
        } else if (message.contains("52002")) {
            return "系统错误，请稍后重试";
        } else if (message.contains("52003")) {
            return "未授权用户，请检查appid和appkey";
        } else if (message.contains("54000")) {
            return "必填参数为空";
        } else if (message.contains("54001")) {
            return "签名错误，请检查密钥配置";
        } else if (message.contains("54003")) {
            return "访问频率受限，请降低请求频率";
        } else if (message.contains("54004")) {
            return "账户余额不足";
        } else if (message.contains("54005")) {
            return "长query请求频繁";
        } else if (message.contains("58000")) {
            return "客户端IP非法";
        } else if (message.contains("58001")) {
            return "译文语言方向不支持";
        } else if (message.contains("58002")) {
            return "服务当前已关闭";
        } else if (message.contains("90107")) {
            return "认证未通过或未生效";
        } else {
            return message;
        }
    }
    
    // 内部类定义
    @Data
    public static class BaiduTranslateResult {
        // Getters and Setters
        private String fromLang;
        private String toLang;
        private java.util.List<BaiduTranslateResponseDTO.TransResult> transResult;
        private long duration;
        private int sourceLength;
        private int index;
        private boolean success = true;
        private String errorMessage;

    }
}